//
//  FMDBHelpr.m
//  WhiteChat
//
//  Created by 胡海政 on 16/3/4.
//  Copyright © 2016年 胡海政. All rights reserved.
//

#import "FMDBHelpr.h"

@implementation FMDBHelpr

static FMDBHelpr *fmdb = nil;
static FMDatabase *db = nil;

+ (instancetype)shareSQLite {
    @synchronized(self) {
        if (fmdb == nil) {
            fmdb = [[FMDBHelpr alloc]init];
            return fmdb;
        } else {
            return fmdb;
        }
    }
}

- (FMDatabase *)openDB {
    if (db != nil) {
        [db open];
        return db;
    } else {
        NSString *documentDirectory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"MyDatabase.db"];
        db = [FMDatabase databaseWithPath:dbPath];
        NSLog(@"%@",dbPath);
        [db open];
        return db;
    }
}
- (void)closeDB {
    [db close];
}


- (void)createTable {
    db = [self openDB];
    NSString *sql = @"create table if not exists downLoad (t_id integer primary key  not null unique,name_zh_cn Varchar not NULL,name_en Varchar not NULL,image_url Varchar not NULL,lat Varchar not NULL,lng Varchar not NULL,contents_count Varchar not NULL)";
    BOOL result = [db executeUpdate:sql];
    if (result) {
        NSLog(@"创建表成功");
    } else {
        NSLog(@"创建表失败");
    }
    [self closeDB];
}

- (void)insertDataWithUser:(strategyModel *)model {
    db = [self openDB];
    NSString *sql = @"INSERT INTO downLoad (name_zh_cn,name_en,image_url,lat,lng) VALUES (?,?,?,?,?)";
    if (sql) {
        [db executeUpdate:sql,model.name_zh_cn,model.name_en,model.image_url,model.lat,model.lng];
        NSLog(@"添加数据成功");
    } else {
        NSLog(@"添加数据失败");
    }
    [self closeDB];
}

- (strategyModel *)seleteUserWithID:(NSInteger)id {
    db = [self openDB];
    FMResultSet *rs = [db executeQuery:@"SELECT t_id,name_zh_cn,name_en,image_url,lat,lng,contents_count FROM downLoad where t_id = ?",id];
    strategyModel *user = [strategyModel new];
    while ([rs next]) {
//        user.username = [rs stringForColumn:@"username"];
//        user.avatarUrl = [rs stringForColumn:@"avatarUrl"];
//        user.userId = userId;
    }
    [self closeDB];
    return user;
}

- (BOOL) deleteTable:(NSString *)tableName{
    db = [self openDB];
    NSString *sqlstr = [NSString stringWithFormat:@"DROP TABLE %@", tableName];
    if (![db executeUpdate:sqlstr])
    {
        
        [self closeDB];
        return NO;
    }
    [self closeDB];
    return YES;
}









@end
